package com.wk.service.impl;

import com.wk.constant.CommonStatusEnum;
import com.wk.constant.IdentityConstant;
import com.wk.constant.VerifyCodeConstant;
import com.wk.dto.ResponseResult;
import com.wk.dto.verificationcode.VerifyCodeResponse;
import com.wk.service.VerifyCodeService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class VerifyCodeServiceImpl implements VerifyCodeService {

	@Autowired
	private StringRedisTemplate redisTemplate;

	@Override
	public ResponseResult<VerifyCodeResponse> generate(int identity, String phoneNumber) {
		//限制验证码发送次数，如果1分钟发送3次，等10分钟再发，5分钟发10次，等24小时

		//生成Redis的key
		String key = generateKeyPreByIdentity(identity)+phoneNumber;

		//生成验证码
		String code = String.valueOf((int)((Math.random()*9+1)*100000));

		//验证码存到Redis中，有效期2分钟
		redisTemplate.boundValueOps(key).set(code, 2, TimeUnit.MINUTES);

		//返回
		return ResponseResult.success(new VerifyCodeResponse(code));
	}

	@Override
	public ResponseResult verify(int identity, String phoneNumber, String code) {
		//判断参数是否为空

		//生成Redis的key
		String key = generateKeyPreByIdentity(identity)+phoneNumber;

		String redisCode = redisTemplate.boundValueOps(key).get();

		if(StringUtils.isNotBlank(code)	&& StringUtils.isNotBlank(redisCode) && code.trim().equals(redisCode.trim())) {
			return ResponseResult.success(null);
		}else {
			return ResponseResult.fail(CommonStatusEnum.VERIFY_CODE_ERROR.getCode(), CommonStatusEnum.VERIFY_CODE_ERROR.getValue());
		}
	}

	/**
	 * 根据身份类型生成对应的缓存key
	 * @param identity
	 * @return
	 */
	private String generateKeyPreByIdentity(int identity){
		String keyPre = "";
		if (identity == IdentityConstant.PASSENGER){
			keyPre = VerifyCodeConstant.PASSENGER_LOGIN_KEY_PRE;
		}else if (identity == IdentityConstant.DRIVER){
			keyPre = VerifyCodeConstant.DRIVER_LOGIN_KEY_PRE;
		}
		return keyPre;
	}
}
